#!/usr/bin/python

import sys

import kconfiglib
from kconfiglib import Kconfig, Symbol, Choice, MENU, COMMENT, TRI_TO_STR


if len(sys.argv) < 3:
    sys.exit('Pass symbol name (without "CONFIG_" prefix) with SCRIPT_ARG=<name>')

kconf = kconfiglib.Kconfig(sys.argv[1], warn=False)
sym_name = sys.argv[2]
if sym_name not in kconf.syms:
    print("No symbol {} exists in the configuration".format(sym_name))
    sys.exit(0)

referencing = [node for node in kconf.node_iter()
               if kconf.syms[sym_name] in node.referenced]
if not referencing:
    print("No references to {} found".format(sym_name)) # PROC_PID_CPUSET
    sys.exit(0)

print("Found {} locations that reference {}:\n"
      .format(len(referencing), sym_name))

for i, node in enumerate(referencing, 1):
    list = []
    print("\n========== Location {} ({}:{}) ==========\n"
          .format(i, node.filename, node.linenr))
    node_config = ("{}".format(str(node).split('help')[0]))

    if isinstance(node.item, Symbol):
        sym = kconf.syms[node.item.name]
        node_config = ("{}\rvalue = {}\nvisibility = {}".format(str(node).split('help')[0],sym.str_value, TRI_TO_STR[sym.visibility]))
    # Print the parents of the menu node too

    node = node.parent
    parent_i = 1
    while node is not kconf.top_node:
        config = ("---------- Parent {} ({}:{})  ----------\n{}"
              .format(parent_i, node.filename, node.linenr, str(node).split('help')[0]))
        if isinstance(node.item, Symbol):
            sym = kconf.syms[node.item.name]
            config = ("{}\rvalue = {}\nvisibility = {}\n".format(config, sym.str_value, TRI_TO_STR[sym.visibility]))
        list.append(config)
        node = node.parent
        parent_i += 1
    list.reverse()
    for info in list:
        print(info)
    print("----------------- CONFIG -------------------")
    print(node_config)
